package com.cjj.common.utils;

import com.cjj.common.consts.PasswordProperties;
import com.cjj.common.framework.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.GeneralSecurityException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * @author DoyuTu
 */
@Component
@Slf4j
public class PasswordUtil {

    private static final String AUTH_KEY = "zlglz&1";

    private static PasswordProperties passwordProperties;

    @Autowired
    public void setPasswordProperties(PasswordProperties passwordProperties) {
        PasswordUtil.passwordProperties = passwordProperties;
    }

    public static String encryptPassword(String password, String encrypt) {
        return DigestUtils.md5Hex(password + encrypt + AUTH_KEY);
    }

    public static void checkSamePassword(String newPassword, String rawPassword, String encrypt) {
        if (StringUtils.equals(encryptPassword(newPassword, encrypt), rawPassword)) {
            throw new BusinessException("不能修改为与原密码相同的密码");
        }
    }

    public static String decryptRsaPassword(String password) {
        try {
            RSAPrivateKey privateKey = RSAUtil.getPrivateKey(passwordProperties.getPrivateKey());
            return RSAUtil.privateDecrypt(password, privateKey);
        } catch (GeneralSecurityException e) {
            // Ignore
            log.error("密码加密失败", e);
        }
        throw new BusinessException("拒绝访问");
    }

    public static String encryptRsaPassword(String password) {
        try {
            RSAPublicKey publicKey = RSAUtil.getPublicKey(passwordProperties.getPublicKey());
            return RSAUtil.publicEncrypt(password, publicKey);
        } catch (GeneralSecurityException e) {
            // Ignore
            log.error("密码加密失败", e);
        }
        throw new BusinessException("拒绝访问");
    }

    public static void checkPassword(String password) {
        if (!password.matches("^(?=.*\\d)(?=.*[a-zA-Z]).{6,20}$")) {
            throw new BusinessException("密码长度为6-20位字符，支持数字、大小写字母、标点符号，不允许空格，必须包含字母和数字");
        }
    }

}
